// 批量调整升贴水
<template>
  <div class="stock">
    <div class="header">
      <span class="label">商品种类：</span>
      <span>{{ quotationData.categoryName }}</span>
    </div>
    <c-table
      :data="tableData"
      :columns="columns"
      key="id"
      :showHeader="false"
      size="small"
      selection
      :selectedRowKeys="selectedKeys"
      @onSelectChange="onSelectChange"
    >
      <template v-slot:newPremium="{ row }">
        <a-input-number
          v-model="row.newPremium"
          :precision="0"
        ></a-input-number>
      </template>
      <template v-slot:premiumTitle>
        <span>{{ quotationData.priceType === 1 ? "原升贴水" : "原价格" }}</span>
      </template>
      <template v-slot:premium="{ row }">
        <span
          >{{ quotationData.priceType === 1 ? row.premium : row.price }}
        </span>
      </template>
      <template v-slot:newPremiumTitle>
        <span
          >{{
            quotationData.priceType === 1
              ? "增加升贴水（减升贴水写负数）"
              : "加价（降价写负数）"
          }}
        </span>
      </template>
    </c-table>
    <div class="footer flex flex-align-c">
      <span class="label"
        >{{
          quotationData.priceType === 1
            ? "批量增加升贴水（减升贴水写负数）："
            : "批量加价（降价写负数）："
        }}
      </span>
      <span>
        <a-input-number
          v-model="batchPremium"
          :precision="0"
          :disabled="selectedKeys.length === 0"
          @change="batchPremiumChange"
        ></a-input-number>
      </span>
    </div>
  </div>
</template>

<script>
import quotationDict from "@/dict/quotation";
import {
  getMyQuotationDetail,
  updatequotationpremium,
  updatequotationprice,
  verifyhistorypremium
} from "@/api/quotation";
import { historyPremiumVerify } from "@/util/mixins/historyPremiumVerify";

export default {
  props: {
    // 报价信息，用于查询子商品
    quotationData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  mixins: [historyPremiumVerify],
  data() {
    return {
      columns: [
        {
          title: "品牌",
          dataIndex: "brand"
        },
        {
          title: "规格",
          dataIndex: "spec"
        },
        {
          title: "材质",
          dataIndex: "material"
        },
        {
          title: "其他",
          dataIndex: "other"
        },
        {
          title: "仓库简称",
          dataIndex: "warehouseName"
        },
        {
          title: "未成交订单数",
          scopedSlots: { customRender: "order" }
        },
        {
          // title: "原升贴水",
          // dataIndex: this.quotationData.priceType === 1 ? "premium" : "price",
          slots: { title: "premiumTitle" },
          scopedSlots: { customRender: "premium" }
        },
        {
          // title: "增加升贴水(减升贴水写负数)",
          slots: { title: "newPremiumTitle" },
          scopedSlots: { customRender: "newPremium" }
        }
      ],
      tableData: [],
      batchPremium: undefined, // 批量调整升贴水
      selectedKeys: [] // 已勾选的商品
    };
  },
  methods: {
    // 重置状态
    resetData() {
      this.selectedKeys = [];
      this.batchPremium = undefined;
    },
    // 获取子商品
    getQuotationDetail() {
      getMyQuotationDetail({
        quotationId: this.quotationData.id
      }).then(res => {
        this.tableData = res.quotationDetailList;
      });
    },
    onSelectChange(rowKeys) {
      this.selectedKeys = rowKeys;
      if (rowKeys.length === 0) this.batchPremium = undefined;
    },
    batchPremiumChange(val) {
      this.tableData.forEach((item, idx) => {
        if (this.selectedKeys.indexOf(item.id) !== -1) {
          this.$set(this.$data.tableData[idx], "newPremium", val);
        }
      });
    },
    // 历史升贴水对比
    historyPremiumVerify() {
      // 转换参数格式
      let params = [];
      this.tableData.forEach(item => {
        let obj = {
          categoryId: this.quotationData.categoryId,
          brand: item.brand,
          spec: item.spec,
          material: item.material,
          warehouseId: item.warehouseId,
          premium: this.$tools.formatFloatFloor(
            Number(item.newPremium || 0) + Number(item.premium)
          )
        };
        params.push(obj);
      });
      verifyhistorypremium(params)
        .then(() => {
          this.submit();
        })
        .catch(err => {
          let _this = this;
          if (err.code === this.$globalSite.errorCode.verifyhistorypremium) {
            let el = this.dealHistoryPremiumVerifyMsg(err.data);
            this.$confirm({
              title: "温馨提示",
              content: el,
              onOk() {
                return new Promise(resolve => {
                  _this.submit().then(() => {
                    resolve();
                  });
                });
              }
            });
          }
        });
    },
    submitVerify() {
      // 修复升贴水需对比历史升贴水
      if (this.quotationData.priceType === 1) {
        this.historyPremiumVerify();
      } else {
        this.submit();
      }
    },
    // 提交调整升贴水/价格
    submit() {
      let name = this.quotationData.priceType === 1 ? "premium" : "price";
      let quotationDetails = this.tableData.map(item => {
        return Object.assign(
          {},
          { id: item.id, [name]: item.newPremium || 0, version: item.version }
        );
      });
      let submitFunc =
        this.quotationData.priceType === 1
          ? updatequotationpremium
          : updatequotationprice;
      return new Promise(resolve => {
        submitFunc({
          quotationId: this.quotationData.id,
          version: this.quotationData.version,
          quotationDetails: quotationDetails
        })
          .then(res => {
            let msg =
              res.quotationType === quotationDict.status.pending.value
                ? "提交成功，等待审核"
                : "操作成功";
            this.resetData();
            this.$message.success(msg);
            this.$emit("success", this.quotationData.id);
          })
          .finally(() => {
            resolve();
          });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.c-table {
  margin: 18px 0;
}
</style>
